import request from '@/utils/request'
import axios from 'axios'

/**
 * 批量上传
 * @param {文件数组} fileArray 
 */
export function uploaders(fileArray,callback) {

		let formData = new FormData();
		fileArray.map((item)=>{
			//files是后台参数name字段对应值
			formData.append('files', item);
		})
    uploaderBatch(formData).then(res => {
      callback(res);
    }).catch(err => {
    	alert(err)
		})
		
}

/**
 * 单个上传
 * @param {文件} file 
 */
export function uploaderSingle(file,callback) {

  let formData = new FormData();
  //files是后台参数name字段对应值
  formData.append('file', file.file);
  uploader(formData).then(res => {
    callback(res);
  }).catch(err => {
    alert(err)
  })
  
}

export function uploader(data) {
  return request({
    headers: {'Content-Type': 'multipart/form-data'},
    url: '/upload/uploadImageToAliyun',
    method: 'post',
    data
  })
}

export function uploaderBatch(data) {
  return request({
    headers: {'Content-Type': 'multipart/form-data'},
    url: '/upload/uploadBatch',
    method: 'post',
    data
  })
}


const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}

const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
  var url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    responseType: 'blob'
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}
